<?php

class ProductoController extends AweController {

    /**
     * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
     * using two-column layout. See 'protected/views/layouts/column2.php'.
     */
    public $layout = '//layouts/column2';
    public $defaultAction = 'admin';

    public function filters()
    {
        return array(
            array('CrugeAccessControlFilter'),
        );
    }

    /**
     * Displays a particular model.
     * @param integer $id the ID of the model to be displayed
     */
    public function actionView($id)
    {
        $this->render('view', array(
            'model' => $this->loadModel($id),
        ));
    }

    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
    public function actionCreate()
    {
        $model = new Producto;


        if (isset($_POST['Producto']))
        {
            $model->attributes = $_POST['Producto'];
            if (CUploadedFile::getInstance($model, 'foto'))
            {
                $path = realpath(Yii::app()->getBasePath() . "/../images/productos/");
                $model->foto = CUploadedFile::getInstance($model, 'foto');
                if ($model->foto !== null)
                {
                    $model->foto->saveAs($path . "/" . $model->id . strrchr($model->foto, '.'));
                    $model->foto = $model->id . strrchr($model->foto, '.');
                }
            }
            if ($model->save())
            {
                //ingresar al kardex
                $kardex = new Kardex();
                $kardex->estado = 'ENTRADA';
                $kardex->producto_id = $model->id;
                $kardex->detalle = 'Saldo inicial';
                $kardex->cantidad = $model->cantidad;
                $kardex->precio_unitario = $model->precio_unitario;
                $kardex->save(false);
                if (isset($_POST['Producto']['facturas']))
                    $model->saveManyMany('facturas', $_POST['Producto']['facturas']);
                if (isset($_POST['Producto']['ordenCompras']))
                    $model->saveManyMany('ordenCompras', $_POST['Producto']['ordenCompras']);
                $this->redirect(array('view', 'id' => $model->id));
            }
        }

        $this->render('create', array(
            'model' => $model,
        ));
    }

    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id the ID of the model to be updated
     */
    public function actionUpdate($id)
    {
        $model = $this->loadModel($id);


        if (isset($_POST['Producto']))
        {
//                    var_dump($GLOBALS);
            $model->attributes = $_POST['Producto'];
            if (CUploadedFile::getInstance($model, 'foto'))
            {
                $path = realpath(Yii::app()->getBasePath() . "/../images/productos/");
                $model->foto = CUploadedFile::getInstance($model, 'foto');
                if ($model->foto !== null)
                {
                    $model->foto->saveAs($path . "/" . $model->id . strrchr($model->foto, '.'));
                    $model->foto = $model->id . strrchr($model->foto, '.');
                }
            }
            if ($model->save())
            {
                if (isset($_POST['Producto']['facturas']))
                    $model->saveManyMany('facturas', $_POST['Producto']['facturas']);
                else
                    $model->saveManyMany('facturas', array());
                if (isset($_POST['Producto']['ordenCompras']))
                    $model->saveManyMany('ordenCompras', $_POST['Producto']['ordenCompras']);
                else
                    $model->saveManyMany('ordenCompras', array());
                $this->redirect(array('view', 'id' => $model->id));
            }
        }

        $this->render('update', array(
            'model' => $model,
        ));
    }

    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'admin' page.
     * @param integer $id the ID of the model to be deleted
     */
    public function actionDelete($id)
    {
        if (Yii::app()->request->isPostRequest)
        {
            // we only allow deletion via POST request
            $this->loadModel($id)->delete();

            // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
            if (!isset($_GET['ajax']))
                $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
        }
        else
            throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
    }

    /**
     * Lists all models.
     */
    public function actionIndex()
    {
        $dataProvider = new CActiveDataProvider('Producto');
        $this->render('index', array(
            'dataProvider' => $dataProvider,
        ));
    }

    /**
     * Manages all models.
     */
    public function actionAdmin()
    {
        $model = new Producto('search');
        $model->unsetAttributes(); // clear any default values
        if (isset($_GET['Producto']))
            $model->attributes = $_GET['Producto'];

        $this->render('admin', array(
            'model' => $model,
        ));
    }

    /**
     * @author John Doe <john.doe@example.com>
     */
    public function actionCatalogo()
    {
        $model = Producto::model()->with('categoria')->findAll(array('condition' => 't.estado = "ACTIVO" AND categoria.estado = "ACTIVO" '));
        $categorias = Categoria::model()->findAll(array('condition' => 'estado = "ACTIVO"'));

        $this->render('catalogo', array(
            'model' => $model,
            'categoria' => $categorias,
        ));
    }

    /**
     * 
     */
    public function actionCargarProducto()
    {
        if ($_POST)
        {
            $proveedor = $_POST['OrdenRequisicion']['proveedor_id'];
            $categoria = $_POST['OrdenRequisicion']['categoria_id'];
            $producto = Yii::app()->db->createCommand()
                    ->select("id , nombre")
                    ->from("producto")
                    ->where("estado = :estado", array(':estado' => 'ACTIVO'))
                    ->order("nombre");
            if ($proveedor)
            {
                $producto->andWhere("proveedor_id=:proveedor", array(':proveedor' => $proveedor));
            }
            if ($categoria)
            {
                $producto->andWhere("categoria_id=:categoria", array(':categoria' => $categoria));
            }

//       $producto->queryAll();
            echo CHtml::tag('option', array('value' => ''), '- Seleccione -', true);
            foreach ($producto->queryAll() as $value)
            {
                echo CHtml::tag('option', array('value' => $value['id']), CHtml::encode($value['nombre']), true);
            }
        }
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer the ID of the model to be loaded
     */
    public function loadModel($id, $modelClass = __CLASS__)
    {
        $model = Producto::model()->findByPk($id);
        if ($model === null)
            throw new CHttpException(404, 'The requested page does not exist.');
        return $model;
    }

    /**
     * Performs the AJAX validation.
     * @param CModel the model to be validated
     */
    protected function performAjaxValidation($model, $form = null)
    {
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'producto-form')
        {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }

}
